<!--
  author: tangcheng_cd
  create by: 2018/5/21
  descr: 用户管理主界面
-->
<template>
  <div id="user-manager">
    <v-header class="pd-left15" title="用户管理" :showDownloadBtn="false" :saveShow="false"></v-header>
    <div class="box">
      <el-row type="flex" class="row-bg" :gutter="20">
        <el-col :span="6" class="org-tree-box">
          <org-tree ref="orgTree"
                    :default-expand-all="defaultExpandAll"
                    @nodeClick="orgTreeNodeClicked"
                    @loaded="orgTreeLoaded">
          </org-tree>
          <!--<org-tree-grid :columns="orgTreeGridColumns"></org-tree-grid>-->
        </el-col>
        <el-col :span="18">
          <el-container class="right-box">
            <el-header class="right-box-header" height="50px">
              <el-row class="toolbar">
                <el-button type="primary" size="mini" @click="addBtnClicked">增加</el-button>
                <el-button type="primary" size="mini" @click="delBtnClicked">删除</el-button>
                <el-button type="primary" size="mini" @click="editBtnClicked">编辑</el-button>
                <el-button type="primary" size="mini" @click="roleSetClicked">分配角色</el-button>
                <el-button type="primary" size="mini" @click="settingTheApp">分配应用</el-button>
                <div class="search-box">
                  <el-input
                    size="mini"
                    placeholder="输入用户账号或姓名搜索"
                    auto-complete="on"
                    v-model="searchText"
                    style="width: 250px"
                  >
                    <el-button type="primary"
                              slot="append"
                              @click="searchTextBtnClicked"
                              icon="el-icon-search"></el-button>
                  </el-input>
                </div>
              </el-row>
            </el-header>
            <el-main class="right-box-main">
              <user-mana-grid ref="userGrid"
                              @changeUserStatus="changeUserStatus"
                              @resetPassword="resetPassword"></user-mana-grid>
            </el-main>
          </el-container>
        </el-col>
      </el-row>
    </div>
    <user-add-modify ref="userForm" @submitAfter="userFormSubmitAfter"></user-add-modify>
    <user-role-setting ref="userRoleSetting"></user-role-setting>
    <app-role-setting ref="appRoleSetting"></app-role-setting>
    <user-reset-password ref="userResetPassword" resetPassword="true"></user-reset-password>
    <setting-the-app ref="settingTheApp"></setting-the-app>
  </div>
</template>

<script type="text/ecmascript-6">
import {VHeader} from '../../../components'
import Msg from '../../../assets/js/msg'
import OrgTree from '../../comm/orgTree'
import UserManaGrid from './userManaGrid'
import userAddModify from './userAddModify'
import api from '../../../api/url'
import ajax from '../../../api/ajax/ajax'
import UserRoleSetting from './userRoleSetting'
import AppRoleSetting from './appRoleSetting'
import UserResetPassword from './userResetPassword'
import settingTheApp from './settingTheApp'

export default {
  name: 'user-manager',
  components: {
    UserResetPassword,
    UserRoleSetting,
    AppRoleSetting,
    userAddModify,
    UserManaGrid,
    OrgTree,
    VHeader,
    settingTheApp
  },
  data () {
    return {
      commonData: [],
      orgTreeGridColumns: [{
        label: '机构名称',
        name: 'name',
        index: 'name'
      }, {
        label: '机构代码',
        name: 'code',
        index: 'code',
        width: '130px'
      }],
      // 默认展开所有
      defaultExpandAll: false,
      // 搜索内容
      searchText: null
    }
  },
  methods: {
    orgTreeLoaded (currTreeNode, datas) {
      // 通过机构树的第一条机构加载用户表格的数据
      this.$refs.userGrid.getPageData({
        orgId: currTreeNode.id
      })
    },
    orgTreeNodeClicked (nodeData, node) {
      this.$refs.userGrid.getPageData({
        orgId: nodeData.id
      })
    },
    addBtnClicked () {
      let curOrgNode = this.$refs.orgTree.getCurrentNode()
      if (!curOrgNode) {
        this.$message.error('请选择左侧一项机名称!')
      } else {
        this.$refs.userForm.addShow(curOrgNode)
      }
    },
    editBtnClicked () {
      let curOrgNode = this.$refs.orgTree.getCurrentNode()
      if (!curOrgNode) {
        this.$message.error('请选择一项机构记录!')
      } else {
        let selUserNode = this.$refs.userGrid.getCurrentNode()
        if (!selUserNode) {
          this.$message.error('请选择一条用户记录进行编辑!')
        } else {
          this.$refs.userForm.editShow(curOrgNode, selUserNode)
        }
      }
    },
    delBtnClicked () {
      let selUserNode = this.$refs.userGrid.getCurrentNode()
      if (!selUserNode) {
        this.$message.error('请选择一条用户记录进行编辑!')
      } else {
        Msg.confirm('是否删除所选用户记录？', {
          onConfirm: () => {
            ajax.post(api.DELETE_SYS_USER, selUserNode).then(res => {
              // 清除当前选择
              this.$refs.userGrid.clearCurrentNode()
              // 刷新数据
              this.$refs.userGrid.getData()

              this.$message.success('删除成功!')
            }).catch(e => {
              // console.error('删除用户记录发生错误！')
            })
          },
          onCancel () {

          }
        })
      }
    },
    // 角色设置按钮处理
    roleSetClicked () {
      let selUserNode = this.$refs.userGrid.getCurrentNode()
      if (!selUserNode) {
        this.$message.error('请选择一位用户!')
      } else {
        this.$refs.userRoleSetting.show(selUserNode)
      }
    },
    // 搜索按钮被点击
    searchTextBtnClicked () {
      // 通过关键字搜索
      this.$refs.userGrid.getDataByKeyword(this.searchText)
    },
    // 改变用户状态 锁定/解锁
    changeUserStatus (user) {
      let status = '2'
      let optStr
      if (user.status === '2') {
        optStr = '解锁此用户'
        status = '1'
      } else {
        optStr = '锁定此用户'
      }
      Msg.confirm(`你确定要${optStr}吗?`, {
        onConfirm () {
          let postData = {
            id: user.id,
            status: status,
            version: user.version
          }
          ajax.post(api.UPDATE_SYS_USER_STATUS, postData).then(res => {
            user.status = status
            // 刷新 (这里应该可以不用刷新，减少一次请求)
            // this.$refs.userGrid.getData()
            this.$message.error(`${optStr}成功!`)
          }).catch(e => {
            // console.error('解锁锁定数据请求发生错误！')
          })
        }
      })
    },
    // 重设密码
    resetPassword (user) {
      let refurp = this.$refs.userResetPassword
      refurp.show({
        onConfirm (newPassword, newPasswordConfirm) {
          let postData = {
            id: user.id,
            failTime: user.failTime,
            password: newPassword,
            password_confirm: newPasswordConfirm // 从form中得
          }
          ajax.post(api.RESET_SYS_USER_PASSWORD, postData).then(res => {
            this.password = postData.password
            this.password_confirm = postData.password_confirm
            // this.$message.info('重设密码成功!')
            refurp.close()
          }).catch(e => {
            console.error('重设密码发生错误！', e)
          })
        }
      })
    },
    // 用户表单提交后回调
    userFormSubmitAfter (dialog) {
      if (dialog.dialogMode === 'ADD') {
        this.$message({
          type: 'success',
          message: '增加成功!'
        })
      } else {
        this.$message({
          type: 'success',
          message: '编辑成功!'
        })
      }
      // 刷新表格数据
      // this.$refs.dataGrid.getData()
      this.$refs.userGrid.getData()
    },
    settingTheApp () {
      let selUserNode = this.$refs.userGrid.getCurrentNode()
      if (!selUserNode) {
        this.$message.error('请选择一个应用!')
      } else {
        this.$refs.appRoleSetting.show(selUserNode)
      }
    }
  },
  created () {
    this.commonData = JSON.parse(sessionStorage.getItem('commonData'))
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus">
#user-manager
  overflow hidden
  font-size 14px
  height 100%
  .pd-left15
    padding-left 15px
  .box
    overflow auto
    height calc(100% - 56px)
    margin 10px 0 0 10px
    padding-right 10px
  .org-tree-box
    background-color #fff
  .right-box
    height 100%
    .right-box-header
      background-color #fff
      margin-bottom 3px
    .toolbar
      position relative
      line-height 50px
      vert-align middle
      .search-box
        position absolute
        top 0
        right 0
    .right-box-main
      padding 0px 0px
      height 100%
      background-color #fff
</style>
